package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;


    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        //判断是否套餐，如果是套餐需要把审核状态修改为初始化
        if(ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT); //把状态设置为初始化
        }else {
            //设置默认的审核状态为无需审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED); //防止其他程序员在地址栏输入参数
        }
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF); //设置默认的销售状态
        serviceItem.setCreateTime(new Date());
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        /*
          1.已上架，不能直接编辑的，需要下架之后才能进行编辑
          2.未上架，但是是套餐且处于审核状态，这时候也不能进行编辑的
          3.如果是未上架，审核通过了，再重新编辑？ 把审核状态修改成初始化
         */
        //根据ID 获取当前 ServiceItem 对象
        ServiceItem oldServiceItem = this.get(serviceItem.getId());

        if(ServiceItem.SALESTATUS_ON.equals(oldServiceItem.getSaleStatus())){
           //说明当前为上架状态，不能进行编辑
            throw  new BusinessException("上架状态，不能进行编辑");
        }
        if(ServiceItem.CARPACKAGE_YES.equals(oldServiceItem.getCarPackage()) && ServiceItem.AUDITSTATUS_AUDITING.equals(oldServiceItem.getAuditStatus())){
            //说明当前是套餐且处于审核中，不能进行编辑
            throw new BusinessException("套餐且处于审核中，不能进行编辑");
        }
        //如果是未上架，审核通过了，再重新编辑？ 把审核状态修改成初始化
        if(ServiceItem.CARPACKAGE_YES.equals(oldServiceItem.getCarPackage()) && ServiceItem.AUDITSTATUS_APPROVED.equals(oldServiceItem.getAuditStatus())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        /*if(ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);*/
        }else {
            //编辑前是什么状态，也设置什么状态 防止地址栏输入
            serviceItem.setAuditStatus(oldServiceItem.getAuditStatus());
        }

        //未上架 才可编辑 防止地址栏输入
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    //上架
    @Override
    public void saleOn(Long id) {
        ServiceItem serviceItem = this.get(id);
        if(ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())){
            //养修服务已经处于上架状态
            throw new BusinessException("养修服务已经处于上架状态");
        }
        if(ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) //是套餐
                && !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())){  //审批未通过
            throw new BusinessException("套餐需要审核通过才能上架");
        }

        //把状态saleStatus 修改上架状态
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);
    }


    //下架
    @Override
    public void saleOff(Long id) {
        //把状态saleStatus 修改下架状态
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    @Transactional
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        //1.合理性效验
        //1下架状态  2是套餐   3初始化状态或审核拒绝
        ServiceItem serviceItem = this.get(id);
        if(ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())  //处于上架
                ||ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage()) //非套餐
                ||ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus()) //处于审核中
                ||ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus()) //处于审核通过
                ||ServiceItem.AUDITSTATUS_NO_REQUIRED.equals(serviceItem.getAuditStatus()) //无需审核
        ){
            throw new BusinessException("非法操作");
        }
        CarPackageAudit carPackageAudit = new CarPackageAudit();
        carPackageAudit.setServiceItemId(id); //服务单项ID
        carPackageAudit.setCreateTime(new Date()); //创建时间
        carPackageAudit.setAuditorId(director); //审核人ID
        carPackageAudit.setBpmnInfoId(bpmnInfoId); //流程定义ID
        carPackageAudit.setInfo(info);//备注信息
        carPackageAudit.setServiceItemName(serviceItem.getName()); //服务单名称
        carPackageAudit.setServiceItemPrice(serviceItem.getDiscountPrice()); //服务单价格
        carPackageAudit.setServiceItemInfo(serviceItem.getInfo()); //服务单项备注信息
        carPackageAudit.setCreator(ShiroUtils.getUser().getUserName());  //创建人当前登录用户

        //保存审核对象
        carPackageAuditService.save(carPackageAudit);


        //启动流程
        //获取bpmnInfo对象
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        Map<String,Object> param = new  HashMap();
        param.put("discountPrice",serviceItem.getDiscountPrice().longValue());
        param.put("director",director);
        if( finance != null){
            param.put("finance",finance);
        }

        //获取流程实例对象
        ProcessInstance processInstance = runtimeService
                .startProcessInstanceByKey(bpmnInfo.getActProcessKey(), String.valueOf(carPackageAudit.getId()), param);
        //审核对象 关联 流程实例ID
        carPackageAudit.setInstanceId(processInstance.getId());

        carPackageAuditService.update(carPackageAudit);
        //服务单项的审核状态修改
        serviceItemMapper.changeAuditStatus(id,ServiceItem.AUDITSTATUS_AUDITING);

    }

    @Override
    public void changeAuditStatus(Long serviceItemId, Integer auditstatus) {
        serviceItemMapper.changeAuditStatus(serviceItemId,auditstatus);
    }
}
